package Servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

import Bean.User;
import Service.UserService;
import ServiceImpl.UserServiceImpl;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String message = "";
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html charset = UTF-8");
		UserService userService = new UserServiceImpl();
		String username = request.getParameter("username");
		String passwd = request.getParameter("passwd");
		String checkbox = request.getParameter("rememenber");
		User user = userService.login(username, passwd);
		if(user != null) {
			message="yes";
			//request.setAttribute("isPass", "True");
			request.setAttribute("message", "yes");
			request.setAttribute("username", username);
			System.out.println("yes");
			request.getSession().setAttribute("nowUser", user); 
			request.getRequestDispatcher("/JudgeRole").forward(request, response);
		} else {
			message="no";
			//request.setAttribute("isPass", "False");
			request.setAttribute("message", "no");
			System.out.println("no");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

}
